package cn.itcast.bos.web.action;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**宣传活动 管理
 * Created by Think on 2017/9/24.
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")

public class PromotionAction extends BaseAction<Promotion> {
    //宣传图片
    private File titleImgFile;
    //宣传图片的文件名称
    private String titleImgFileFileName;

    public void setTitleImgFile(File titleImgFile) {
        this.titleImgFile = titleImgFile;
    }

    public void setTitleImgFileFileName(String titleImgFileFileName) {
        this.titleImgFileFileName = titleImgFileFileName;
    }

    @Autowired
    private PromotionService promotionService;

    @Action(value = "promotion_save",results = {@Result(name = SUCCESS,type = "redirect",location = "./pages/take_delivery/promotion.html")})
    public String save() throws IOException {
        // 宣传图 上传、在数据表保存 宣传图路径
        // 绝对路径（用于上传）
        String savePath = ServletActionContext.getServletContext().getRealPath("/upload/");
        // 相对路径（用于保存数据库）
        String saveUrl = ServletActionContext.getRequest().getContextPath()+ "/upload/";
        //生成随机图片名
        UUID uuid = UUID.randomUUID();
        String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
        String fileName=uuid+ext;
        File destFile = new File(savePath + "/" + fileName);
        System.out.println(destFile.getAbsolutePath());
        FileUtils.copyFile(titleImgFile, destFile);
        // 将保存路径 相对工程web访问路径，保存model中
        model.setTitleImg(saveUrl + fileName);
        // 调用业务层，完成活动任务数据保存
        promotionService.save(model);
        return SUCCESS;
    }

    //后台宣传商品的分页查询
    @Action(value = "promotion_pageQuery",results = {@Result(name = SUCCESS,type = "json")})
    public String pageQuery(){
        Pageable pageable = new PageRequest(page-1,rows);
        // 调用业务层 完成查询
        Page<Promotion> pageData =  promotionService.findPageData(pageable);
        //压入值栈
        pushPageDataToValueStack(pageData);
        return SUCCESS;
    }
}
